package com.equipmentRent.web.controller.system;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.equipmentRent.common.utils.ShiroUtils;
import com.equipmentRent.system.domain.LeaseRecord;
import com.equipmentRent.system.domain.Order;
import com.equipmentRent.system.domain.OrderDetail;
import com.equipmentRent.system.domain.VO.RtnRecordVo;
import com.equipmentRent.system.service.ILeaseRecordService;
import com.equipmentRent.system.service.IOrderDetailService;
import com.equipmentRent.system.service.IOrderService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.equipmentRent.common.annotation.Log;
import com.equipmentRent.common.enums.BusinessType;
import com.equipmentRent.system.domain.ReturnRecord;
import com.equipmentRent.system.service.IReturnRecordService;
import com.equipmentRent.common.core.controller.BaseController;
import com.equipmentRent.common.core.domain.AjaxResult;
import com.equipmentRent.common.utils.poi.ExcelUtil;
import com.equipmentRent.common.core.page.TableDataInfo;

import javax.annotation.Resource;
import javax.xml.ws.RequestWrapper;

/**
 * 物品归还记录Controller
 * 
 * @author ruoyi
 * @date 2025-05-28
 */
@Controller
@RequestMapping("/system/return")
public class ReturnRecordController extends BaseController
{
    private String prefix = "system/return";

    @Autowired
    private IReturnRecordService returnRecordService;

    @Resource
    private IOrderService orderService;

    @Resource
    private IOrderDetailService orderDetailService;

    @Resource
    private ILeaseRecordService leaseRecordService;

    @RequiresPermissions("system:return:view")
    @GetMapping()
    public String get()
    {
        return prefix + "/return";
    }

    /**
     * 查询物品归还记录列表
     */
    @RequiresPermissions("system:return:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ReturnRecord returnRecord)
    {
        startPage();
        List<RtnRecordVo> list = returnRecordService.selectReturnRecordVoList(returnRecord);
        return getDataTable(list);
    }

    /**
     * 导出物品归还记录列表
     */
    @RequiresPermissions("system:return:export")
    @Log(title = "物品归还记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ReturnRecord returnRecord)
    {
        List<ReturnRecord> list = returnRecordService.selectReturnRecordList(returnRecord);
        ExcelUtil<ReturnRecord> util = new ExcelUtil<ReturnRecord>(ReturnRecord.class);
        return util.exportExcel(list, "物品归还记录数据");
    }

    /**
     * 新增物品归还记录
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("leaseRecordList",leaseRecordService.selectLeaseRecordList(new LeaseRecord()));
        return prefix + "/add";
    }

    /**
     * 新增保存物品归还记录
     */
    @RequiresPermissions("system:return:add")
    @Log(title = "物品归还记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult addSave(ReturnRecord returnRecord)
    {
//        修改订单状态
        LeaseRecord leaseRecord = leaseRecordService.selectLeaseRecordById(returnRecord.getLeaseId());
        if (Objects.isNull(leaseRecord)){
            return error("未查询到关联订单信息");
        }
        Order order = orderService.selectOrderById(leaseRecord.getOrderId());
        OrderDetail orderDetail = orderDetailService.selectOrderDetailByOrderIdAndItemIdByReturn(leaseRecord.getOrderId(), leaseRecord.getItemId());
//        修改子表状态
        orderDetail.setStatus(3L);
//        判断是否逾期
        Date returnTime = returnRecord.getReturnTime();
        Date actualReturn = order.getLeaseEnd();
        order.setActualReturn(returnTime);
        if (returnTime.getTime() > actualReturn.getTime()){
//            计算超期几天
            long days = (returnTime.getTime() - actualReturn.getTime()) / (1000 * 60 * 60 * 24);
            order.setOverdueFee(order.getOverdueFee().add(orderDetail.getDailyRate().multiply(new BigDecimal(days))));
            returnRecord.setIsOverdue(1);
            returnRecord.setOperator(getSysUser().getUserName());
        }
//        修改主表状态 如果待归还的为空 即订单完成
        List<OrderDetail> orderDetails = orderDetailService.selectOrderDetailByOrderIdAndStatus(order.getId(), 1L);
        if (CollectionUtils.isEmpty(orderDetails)){
            order.setStatus(2);
        }

        orderService.updateOrder(order);
        orderDetailService.updateOrderDetail(orderDetail);
        leaseRecord.setLeaseStatus(2);
        leaseRecordService.updateLeaseRecord(leaseRecord);
//        更新订单主表 子表 信息
        String userName = ShiroUtils.getSysUser().getUserName();
        returnRecord.setOperator(userName);
        return toAjax(returnRecordService.insertReturnRecord(returnRecord));
    }

    /**
     * 修改物品归还记录
     */
    @RequiresPermissions("system:return:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ReturnRecord returnRecord = returnRecordService.selectReturnRecordById(id);
        mmap.put("leaseRecordList",leaseRecordService.selectLeaseRecordList(new LeaseRecord()));
        mmap.put("returnRecord", returnRecord);
        return prefix + "/edit";
    }

    /**
     * 修改保存物品归还记录
     */
    @RequiresPermissions("system:return:edit")
    @Log(title = "物品归还记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ReturnRecord returnRecord)
    {
        String userName = ShiroUtils.getSysUser().getUserName();
        returnRecord.setOperator(userName);
        return toAjax(returnRecordService.updateReturnRecord(returnRecord));
    }

    /**
     * 删除物品归还记录
     */
    @RequiresPermissions("system:return:remove")
    @Log(title = "物品归还记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(returnRecordService.softDeleteReturnRecordByIds(ids));
    }
}
